package com.jhd.jiangxi.activity.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.android.material.tabs.TabLayout;
import com.jhd.jiangxi.R;
import com.jhd.jiangxi.UtilHelper;
import com.jhd.jiangxi.activity.scan.check.CheckActivity;
import com.jhd.jiangxi.activity.scan.checkout.CheckOutActivity;
import com.jhd.jiangxi.activity.scan.discern.ScanDiscernActivity;
import com.jhd.jiangxi.activity.scan.in.allot.AllotInActivity;
import com.jhd.jiangxi.activity.scan.in.gift.GiftInActivity;
import com.jhd.jiangxi.activity.scan.in.purchase.PurchaseActivity;
import com.jhd.jiangxi.activity.scan.in.recall.RecallInActivity;
import com.jhd.jiangxi.activity.scan.in.returns.ReturnInActivity;
import com.jhd.jiangxi.activity.scan.in.scrap.ScrapInActivity;
import com.jhd.jiangxi.activity.scan.loss.ScanLossActivity;
import com.jhd.jiangxi.activity.scan.out.allot.AllotOutActivity;
import com.jhd.jiangxi.activity.scan.out.damage.DamageOutActivity;
import com.jhd.jiangxi.activity.scan.out.issue.IssueActivity;
import com.jhd.jiangxi.activity.scan.in.supply.SupplyActivity;
import com.jhd.jiangxi.activity.scan.out.recall.RecallOutActivity;
import com.jhd.jiangxi.activity.scan.out.returns.ReturnOutActivity;
import com.jhd.jiangxi.activity.scan.out.ruin.RuinOutActivity;
import com.jhd.jiangxi.activity.scan.out.scrap.ScrapOutActivity;
import com.jhd.jiangxi.activity.scan.out.spot.SpotOutActivity;
import com.jhd.jiangxi.activity.scan.out.supply.SupplyOutActivity;
import com.jhd.jiangxi.activity.scan.remove.RemoveActivity;
import com.jhd.jiangxi.service.GetMenuAuthService;
import com.jhd.jiangxi.service.GetUserInfoService;
import com.jhd.jiangxi.vo.JsonForResult;
import com.jhd.jiangxi.vo.MainImg;
import com.jhd.jiangxi.vo.NameAndImg;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.jiangxi.vo.MainImg.showType;

/*主界面,启动打开的Activity,测试阶段把更新版本的功能注销了*/
public class MainActivity extends BaseActivity implements View.OnClickListener {
    private Context context=MainActivity.this;
    private FragmentPagerAdapter adapter;
    private ViewPager vp;
    private MainFragment mainFragment;
    private SettingFragment settingFragment;
    private List<Fragment> mDatas = new ArrayList<Fragment>();
    private TabLayout tabs;
    private List<NameAndImg> nameAndImgList=new ArrayList();
    private List<NameAndImg> nameAndImgList2=new ArrayList();
    private AlertDialog _alertDialog = null; //单选框
    @BindView(R.id.tvHeaderUserName)TextView tvMainUserName;
    @BindView(R.id.tvHeaderDeptName)TextView tvMainDeptName;
    @BindView(R.id.btnBack)ImageView btnBack;
    private RecyclerView recycler_view;
    private RelativeLayout relConfig,relAbout,relSecret;//setting fragment
    private TextView tvChange,tvQuit;
    private ProgressDialog _progressDialog;

    @OnClick(R.id.btnBack)
    public void onViewBack(View view) {
        finish();
    }

    @Override
    public void fragmentCreated(View view) {
        super.fragmentCreated(view);
        //setAuth();
        showType(nameAndImgList,application);
        recycler_view=(RecyclerView)view.findViewById(R.id.recycler_view);
        GridLayoutManager layoutManage = new GridLayoutManager(context, 3);
        recycler_view.setLayoutManager(layoutManage);
        RecyclerAdapter recyclerAdapter=new RecyclerAdapter(nameAndImgList);
        recycler_view.setAdapter(recyclerAdapter);
    }
    @Override
    public void fragmentCreated2(View view) {
        super.fragmentCreated2(view);
        relConfig=(RelativeLayout)view.findViewById(R.id.relConfig);
        relConfig.setOnClickListener((View.OnClickListener) context);
        relAbout=(RelativeLayout)view.findViewById(R.id.relAbout);
        relAbout.setOnClickListener((View.OnClickListener) context);
        relSecret=(RelativeLayout)view.findViewById(R.id.relSecret);
        relSecret.setOnClickListener((View.OnClickListener) context);
        tvChange=(TextView)view.findViewById(R.id.tvChange);
        tvChange.setOnClickListener((View.OnClickListener) context);
        tvQuit=(TextView)view.findViewById(R.id.tvQuit);
        tvQuit.setOnClickListener((View.OnClickListener) context);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.relConfig:
                startActivity(new Intent(context,ConfigActivity.class));
                break;
            case R.id.tvQuit://退出登录
                application.clearAll();
                isLogined(application.getUserId());
                break;
            case R.id.tvChange://更换用户
                break;
        }

    }
    private void setAuth(){
        _progressDialog = new ProgressDialog(MainActivity.this);
        _progressDialog.setMessage("正在获取用户权限信息,请稍等...");
        _progressDialog.show();
        String baseUrl = UtilHelper.baseUrls.API(application.getBackSystem());
        Retrofit retrofit= UtilHelper.retrofit(application,baseUrl);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = null;
        GetMenuAuthService ma = retrofit.create(GetMenuAuthService.class);
        jsonForResultCall = ma.getSysResourceByUserIdForPda(token);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                if (_progressDialog != null) _progressDialog.cancel();
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if (jsonForResult.getData() != null) {
                            List<Map> ds = JSON.parseArray(jsonForResult.getData().toString(), Map.class);
                            if (ds.size() > 0) {//如果有设置，才去让菜单显示或隐藏,如果没有配置,默认为显示所有菜单
                                for (NameAndImg nameAndImg : nameAndImgList) {
                                    String mName=nameAndImg.getName();
                                    for (Map d : ds) {
                                        String name = d.get("name") == null ? "" : d.get("name").toString();
                                        if(name.equals(mName)){
                                            nameAndImgList2.add(nameAndImg);
                                        }
                                    }
                                }
                                RecyclerAdapter recyclerAdapter=new RecyclerAdapter(nameAndImgList2);
                                recycler_view.setAdapter(recyclerAdapter);
                            }
                        }
                    } else {
                        String msg = "调用权限接口失败.是否重新刷新权限设置?";
                        if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                            msg = jsonForResult.getMessage() + msg;
                        }
                        UtilHelper.dialogSelector(MainActivity.this, "刷新", msg, new RefreshAuth());
                    }

                } catch (Exception e) {
                    String msg = e.getMessage() + "\r\n调用权限接口失败.是否重新刷新权限设置?点击确定重新刷新;点击取消将没有任何菜单权限.";
                    UtilHelper.dialogSelector(MainActivity.this, "刷新", msg, new RefreshAuth());
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                if (_progressDialog != null) _progressDialog.cancel();
                String msg = t.getMessage() + "调用权限接口失败.是否重新刷新权限设置?";
                UtilHelper.dialogSelector(MainActivity.this, "刷新", msg, new RefreshAuth());
            }
        });
    }
    private class RefreshAuth implements UtilHelper.SelectOK{
        @Override
        public void execute() {
            //setAuth();
        }
    }

    private boolean checkName(String name){
        for (NameAndImg nameAndImg : nameAndImgList) {
            if(nameAndImg.getName().equals(name)){
                nameAndImgList.remove(nameAndImg);
                return true;
            }
        }
        return false;
    }


    /*首页9宫格的adapter*/
    public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
        private List<NameAndImg> nameAndImgList;
        public RecyclerAdapter(List<NameAndImg> nameAndImgList) {
            this.nameAndImgList = nameAndImgList;
        }
        @NonNull
        @Override
        public RecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_main, parent, false);
            RecyclerAdapter.ViewHolder viewHolder = new RecyclerAdapter.ViewHolder(itemView);
            return viewHolder;
        }
        @Override
        public void onBindViewHolder(@NonNull RecyclerAdapter.ViewHolder holder, int position) {
            holder.tv_name.setText(nameAndImgList.get(position).getName());
            holder.ivImg.setBackgroundResource(nameAndImgList.get(position).getImage());
            if(position%3==2){
                holder.right.setVisibility(View.GONE);
            }
            holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(nameAndImgList.get(position).getName().equals("供应入库")){
                        startActivity(new Intent(context,SupplyActivity.class));
                        //overridePendingTransition(R.anim.in_left,R.anim.out_left);
                    }else if(nameAndImgList.get(position).getName().equals("采购入库")){
                        startActivity(new Intent(context,PurchaseActivity.class));
                    }else if(nameAndImgList.get(position).getName().equals("退货入库")){
                        startActivity(new Intent(context, ReturnInActivity.class));
                    }else if(nameAndImgList.get(position).getName().equals("供应出库")){
                        startActivity(new Intent(context, SupplyOutActivity.class));
                    }else if(nameAndImgList.get(position).getName().equals("退货出库")){
                        startActivity(new Intent(context, ReturnOutActivity.class));
                    }else if(nameAndImgList.get(position).getName().equals("移库")){
                        startActivity(new Intent(context, RemoveActivity.class));
                    }else if(nameAndImgList.get(position).getName().equals("盘盈入库")){
                        startActivity(new Intent(context, CheckActivity.class));
                    }else if(nameAndImgList.get(position).getName().equals("盘亏出库")){
                        startActivity(new Intent(context, CheckOutActivity.class));
                    }else if(nameAndImgList.get(position).getName().equals("报废入库")){
                        startActivity(new Intent(context, ScrapInActivity.class));
                    }else if(nameAndImgList.get(position).getName().equals("报废出库")){
                        startActivity(new Intent(context, ScrapOutActivity.class));
                    }else if(nameAndImgList.get(position).getName().equals("损坏出库")){
                        startActivity(new Intent(context, DamageOutActivity.class));
                    }else if(nameAndImgList.get(position).getName().equals("销毁出库")){
                        startActivity(new Intent(context, RuinOutActivity.class));
                    }else if(nameAndImgList.get(position).getName().equals("调拨出库")){
                        startActivity(new Intent(context, AllotOutActivity.class));
                    }else if(nameAndImgList.get(position).getName().equals("调拨入库")){
                        startActivity(new Intent(context, AllotInActivity.class));
                    }else if(nameAndImgList.get(position).getName().equals("召回入库")){
                        startActivity(new Intent(context, RecallInActivity.class));
                    }else if(nameAndImgList.get(position).getName().equals("赠品入库")){
                        startActivity(new Intent(context, GiftInActivity.class));
                    }else if(nameAndImgList.get(position).getName().equals("召回出库")){
                        startActivity(new Intent(context, RecallOutActivity.class));
                    }else if(nameAndImgList.get(position).getName().equals("抽检出库")){
                        startActivity(new Intent(context, SpotOutActivity.class));
                    }
                }
            });
        }
        @Override
        public int getItemCount() {
            return nameAndImgList.size();
        }
        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_name;ImageView ivImg;View right;RelativeLayout relativeLayout;
            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_name = itemView.findViewById(R.id.tv_name);
                this.ivImg = itemView.findViewById(R.id.ivImg);
                this.right = itemView.findViewById(R.id.right);
                this.relativeLayout = itemView.findViewById(R.id.linearLayout);
            }
        }
    }
    private void initView() {
        vp = (ViewPager) findViewById(R.id.vpSheet);
        mainFragment = new MainFragment();
        settingFragment = new SettingFragment();
        mDatas.add(mainFragment);
        mDatas.add(settingFragment);
        tabs = findViewById(R.id.tabSheet);
    }
    @SuppressLint("ResourceType")
    private void initEvent() {
        tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
//                添加选中Tab的逻辑
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
//                添加未选中Tab的逻辑
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
//                再次选中tab的逻辑
            }
        });
        adapter = new FragmentPagerAdapter(getSupportFragmentManager(),1) {
            @Override
            public int getCount() {
                return mDatas.size();
            }

            @Override
            public Fragment getItem(int position) {
                return mDatas.get(position);
            }
        };
        vp.setAdapter(adapter);
        tabs.setupWithViewPager(vp);
        for (int i = 0; i < mDatas.size(); i++) {
            TabLayout.Tab tab = tabs.getTabAt(i);
            View view=  LayoutInflater.from(context).inflate(R.layout.item_main_tab,null);
            tab.setCustomView(view);
            ImageView iv = (ImageView)(view.findViewById(R.id.ivImg));
            TextView tv = (TextView)(view.findViewById(R.id.tv_name));
            if(i==0){
                tv.setText("首页");
                iv.setImageResource(R.drawable.tab_main_img);
            }else if(i==1){
                tv.setText("设置");
                iv.setImageResource(R.drawable.tab_setting_img);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String userId = application.getUserId();
        if (!isLogined(userId)) {
            //isLogined方法里已经添加了跳转和finish方法
        } else {
            setContentView(R.layout.activity_main);
            ButterKnife.bind(this);
            String userName = application.getUserName();
            String deptName = application.getDeptName();
            tvMainDeptName.setText(deptName);
            if (application.getRealName() != null) {
                userName = application.getRealName();
                tvMainUserName.setText(userName);
//                toConfig();
            } else {//如果有登录记录,再获取用户信息,并开始检测是否需要升级
                //new UpdateManager(this).checkUpdate(false);//检测是否需要更新
                getUserInfo();//获取用户信心
            }
            if ("0".equals(application.getBackSystem())) userName = userName + "(测试版本)";
            initView();
            initEvent();
        }
    }

    /*判断缓存,如果有没有的数据,去ConfigActivity配置数据*/
    private void toConfig() {
        application.isConfigEditor();
        //通过历名记录缓存,已设好了默认值的，则不需要再进入默认配置界面设置操作了
        if (application.getConfigApprovalId() == null || application.getConfigStorageId() == null
                || application.getConfigVaccineTypeId() == null || application.getConfigDeptId() == null||application.getConfigPriceId()==null) {
            Intent intent = new Intent(context, ConfigActivity.class);
            super.startActivityForResult(intent, 1);
        }
    }

    /*从ConfigActivity返回*/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        versionTitle();
        if (resultCode == RESULT_FIRST_USER) {//第一次进入，还没有完成配置就返回，需要退回登录界面
            application.clearAll();
            isLogined(application.getUserId());
        }
    }

    /*判断是否是测试版本*/
    private void versionTitle() {
        if ("0".equals(application.getBackSystem())) {
            String userName = application.getUserName();
            if (application.getRealName() != null) userName = application.getRealName();
            tvMainUserName.setText(userName + "(测试版本)");
        }
    }

    /*未登录（这里用自己的登录逻辑去判断是否未登录*/
    private boolean isLogined(String userId) {
        if (null == userId) {
            Intent intent = new Intent(context, LoginActivity.class);
            super.startActivity(intent);
            finish();//跳转到LoginActivity,并关闭本activity
            return false;
        }
        return true;
    }

    /*判断是否打开摄像头权限，没有就打开*/
    private boolean valid() {
        boolean camflag = false;
        boolean memflag = false;
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //先判断有没有权限 ，没有就在这里进行权限的申请
            ActivityCompat.requestPermissions((Activity) context, new String[]{android.Manifest.permission.CAMERA}, 1);
        } else {
            camflag = true;//说明已经获取到摄像头权限了
        }
        //读写内存权限
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // 请求权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
        }

        int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            return false;
        } else {
            // 已申请权限直接跳转到下一个界面
            memflag = true;
        }
        if (camflag && memflag) return true;
        return false;
    }

    /*获取权限的结果返回*/
    @SuppressLint("NewApi")
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 1) {
            boolean camflag = false;
            boolean memflag = false;
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (permissions[0].equals("android.permission.WRITE_EXTERNAL_STORAGE")) {
                    memflag = true;
                } else if (permissions[0].equals("android.permission.CAMERA")) {
                    camflag = true;
                }
            } else {
                Toast.makeText(this,
                        "CAMERA PERMISSION DENIED", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /*获取用户信息,调用回调函数*/
    private void getUserInfo() {
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API(application.getBackSystem()));
        GetUserInfoService vs = retrofit.create(GetUserInfoService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("userId", application.getUserId()).addParam("deptId", application.getDeptId());
        Call<JsonForResult> jsonForResultCall = vs.getSysUserInfo(application.getAccessToken(), params);
        jsonForResultCall.enqueue(new getUserInfoCallback());
    }

    /*获取用户信息的回调*/
    private class getUserInfoCallback implements Callback<JsonForResult> {
        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                    Map<String, Object> info = JSON.parseObject(jsonForResult.getData().toString(), Map.class);
                    if (info != null && info.get("name") != null) {
                        String realName = info.get("name").toString();
                        application.setRealName(realName);
                        tvMainUserName.setText(realName);
                    } else {
                        application.setRealName(application.getUserName());
                    }
                } else {
                    application.setRealName(application.getUserName());
                }
//                toConfig();
            } catch (Exception e) {
                application.setRealName(application.getUserName());
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            application.setRealName(application.getUserName());
        }
    }
}
